package com.wu.util;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.wu.error.BusinessException;
import com.wu.error.EnumBusinessError;
import com.wu.pojo.model.UserToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author: 吴磊
 * @program: blog
 * @create: 2021-04-19 21:44
 */
@Component
public class FTPUtil {

    @Autowired
    private TokenUtils tokenUtils;

    //服务器ip
    @Value("${ftpCentos.host}")
    private String host;
    //服务器端口
    @Value("${ftpCentos.port}")
    private Integer port;
    //服务器登录用户名
    @Value("${ftpCentos.user}")
    private String user;
    //服务器登录密码
    @Value("${ftpCentos.password}")
    private String password;
    //服务器上传路径
    @Value("${ftpCentos.basePath}")
    private String basePath;

    @Value("${ftpCentos.basePath2}")
    private String basePath2;

    public void sshSftp(byte[] bytes, String fileName, String path) throws Exception {
        if (StringUtils.isEmpty(fileName)) {
            throw new BusinessException(EnumBusinessError.UNKNOWN_ERROR, "文件名不能为空");
        }

        Session session;
        Channel channel = null;
        JSch jsch = new JSch();
        if (port <= 0) {
            //连接服务器，采用默认端口
            session = jsch.getSession(user, host);
        } else {
            //采用指定的端口连接服务器
            session = jsch.getSession(user, host, port);
        }

        //如果服务器连接不上，则抛出异常
        if (session == null) {
            throw new BusinessException(EnumBusinessError.UNKNOWN_ERROR, "连接不上服务器");
        }
        //设置登陆主机的密码
        session.setPassword(password);
        //设置第一次登陆的时候提示，可选值：(ask | yes | no)
        session.setConfig("StrictHostKeyChecking", "no");
        //设置登陆超时时间
        try {
            session.connect(30000);
        } catch (Exception e) {
            throw new BusinessException(EnumBusinessError.UNKNOWN_ERROR, "连接超时");
        }
        OutputStream outstream = null;
        try {
            //创建sftp通信通道
            channel = session.openChannel("sftp");
            channel.connect(1000);
            ChannelSftp sftp = (ChannelSftp) channel;
            //进入服务器指定的文件夹
            try {
                sftp.cd(path);
            } catch (Exception e) {
                sftp.mkdir(path);
                sftp.cd(path);
            }
            //以下代码实现从本地上传一个文件到服务器，如果要实现下载，对换以下流就可以了
            outstream = sftp.put(fileName);
            outstream.write(bytes);
            outstream.flush();

        } catch (Exception e) {
            throw new BusinessException(EnumBusinessError.UNKNOWN_ERROR, e.getMessage());
        } finally {
            //关流操作
            if (outstream != null) {
                outstream.flush();
                outstream.close();
            }
            if (session != null) {
                session.disconnect();
            }
            if (channel != null) {
                channel.disconnect();
            }
        }
    }

    /**
     * 上传文件
     *
     * @param file
     * @return 返回文件路径
     * @throws BusinessException
     */
    public String uploadFolder(MultipartFile file) {
        try {
            String stringDir = getStringDir();
            UserToken userToken = tokenUtils.parseTokenToUserToken();
            String userId = userToken.getUserId();
            byte[] bytes = file.getBytes();
            String filename = file.getOriginalFilename();
            String newName = userId + filename.substring(filename.lastIndexOf('.'));
            sshSftp(bytes, newName, basePath + stringDir);
            return "https://image.leistudy.online/image/blog/user/" + stringDir + newName;
        } catch (Exception e) {
            throw new BusinessException(EnumBusinessError.UNKNOWN_ERROR, "文件大小最大为10M");
        }
    }

    /**
     * 上传文件(编写博客时候)
     *
     * @param file
     * @return 返回文件路径
     * @throws BusinessException
     */

    public String uploadFolderWithArticle(MultipartFile file) {
        try {
            String stringDir = getStringDir();
            byte[] bytes = file.getBytes();
            String filename = file.getOriginalFilename();
            String newName = getFileId() + filename.substring(filename.lastIndexOf('.'));
            sshSftp(bytes, newName, basePath2 + stringDir);
            return "https://image.leistudy.online/image/blog/article/" + stringDir + newName;
        } catch (Exception e) {
            throw new BusinessException(EnumBusinessError.UNKNOWN_ERROR, "文件大小最大为10M");
        }
    }

    public static String getStringDir() {
        return new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/";
    }

    public static String getFileId() {
        return IdWorker.get32UUID();
    }

}

